package com.muc.plugin.handler;

import java.util.Collection;
import java.util.List;
import java.util.Map;

import org.dom4j.Element;
import org.jivesoftware.openfire.IQHandlerInfo;
import org.jivesoftware.openfire.XMPPServer;
import org.jivesoftware.openfire.auth.UnauthorizedException;
import org.jivesoftware.openfire.handler.IQHandler;
import org.jivesoftware.openfire.muc.spi.LocalMUCRoom;
import org.jivesoftware.openfire.muc.spi.MultiUserChatServiceImpl;
import org.jivesoftware.openfire.user.User;
import org.jivesoftware.openfire.user.UserManager;
import org.jivesoftware.openfire.user.UserNotFoundException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xmpp.packet.IQ;
import org.xmpp.packet.JID;

import com.muc.plugin.dao.CommonDAO;
import com.muc.plugin.dao.MUCDao;
import com.muc.plugin.dao.hander.SQLConstant;
import com.muc.plugin.vo.PubEntity;
import org.xmpp.packet.PacketError;

/**
 * <iq id='9WDZb-10' type='set'>
 *   <query xmlns='xls:muc-member-query'>
 *     <roomJid>admin</roomJid>
 *   </query>
 * </iq>
 * 成功返回：
 * <iq type="result" id="VCdqw-10" to="admin@gbei.com/Smack">
 *   <query xmlns="xls:muc-member-query">
 *    <members>
 *      <admin>
 *        <jid username="03516a7f8799749d7c53b6be9ffda365@gbei.com" nickname="" />
 *      </admin>
 *      <member>
 *        <jid username="056e0438ac38dc4ddc2bd7f439c9e778@gbei.com" nickname="" />
 *      </member>
 *      <owner>
 *        <jid username="admin@gbei.com" nickname="我是谁?" />
 *      </owner>
 *    </members>
 *   </query>
 * </iq>
 * MUC群 成员获取 包括：管理员 、成员、创建人
 */
public class MUCMemberQueryIQHandler extends IQHandler {

    private IQHandlerInfo info;

    private static final String NAME_SPACE = "xls:muc-member-query";

    private static final String MODULE_NAME = "jid join rooms query";

    private static final Logger log = LoggerFactory.getLogger(MUCMemberQueryIQHandler.class);

    public MUCMemberQueryIQHandler() {
        super(MODULE_NAME);
        info = new IQHandlerInfo("query", NAME_SPACE);
    }

    @Override
    public IQHandlerInfo getInfo() {
        return info;
    }

    @Override
    public IQ handleIQ(IQ packet) throws UnauthorizedException {
        log.info("execute 获取群成员信息 method: handleIQ");
        IQ reply = IQ.createResultIQ(packet);
        reply.setChildElement("query", NAME_SPACE);

        Element iq = packet.getElement();
        Element query = iq.element("query");
        Element roomJidElm = query.element("roomJid");
        if (null == roomJidElm) {
            reply.setError(PacketError.Condition.item_not_found);
            return reply;
        }

        String roomJid = roomJidElm.getText();
        if (null != roomJid && !("".equals(roomJid))) {
            Map<String, String> map = MUCDao.getMUC(roomJid);
            if (null != map) {
                XMPPServer server = XMPPServer.getInstance();
                MultiUserChatServiceImpl mucService = (MultiUserChatServiceImpl) server.getMultiUserChatManager().getMultiUserChatService(Long.parseLong(map.get("serviceID")));
                LocalMUCRoom room = (LocalMUCRoom) mucService.getChatRoom(map.get("name"));
                //添加成员
                Element roome = reply.getChildElement().addElement("members");
                //管理员
                Collection<JID> admins = room.getAdmins();
                if (admins != null && admins.size() > 0) {
                    Element adminE = roome.addElement("admin");
                    for (JID admin : admins) {
                        String jid = admin.toBareJID();
                        String name = MUCDao.getMemberGroupNickNameByRoomIdAndUserId(jid.substring(0, jid.indexOf("@")), roomJid);
                        adminE.addElement("jid")
                                .addAttribute("username", jid)
                                .addAttribute("nickname", null == name ? "" : name);
                    }
                }
                //成员
                List<PubEntity> members = CommonDAO.query(SQLConstant.MEMBER_QUERY, new Object[]{map.get("roomid")});
                if (members != null && members.size() > 0) {
                    Element memberE = roome.addElement("member");
                    for (PubEntity member : members) {
                        try {
                            String jid = member.getColumnValue("jid").toString();
                            String name = MUCDao.getMemberGroupNickNameByRoomIdAndUserId(jid.substring(0, jid.indexOf("@")), roomJid);
                            memberE.addElement("jid")
                                    .addAttribute("username", jid)
                                    .addAttribute("nickname", null == name ? "" : name);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
                //拥有者
                Collection<JID> owners = room.getOwners();
                if (owners != null && owners.size() > 0) {
                    Element ownerE = roome.addElement("owner");
                    for (JID owner : owners) {
                        String name = MUCDao.getMemberGroupNickNameByRoomIdAndUserId(owner.getNode(), roomJid);
                        ownerE.addElement("jid")
                                .addAttribute("username", owner.toBareJID())
                                .addAttribute("nickname", null == name ? "" : name);
                    }
                }
                reply.setType(IQ.Type.result);
                log.info("success result: " + reply.toXML());
                return reply;
            }
        }
        reply.setType(IQ.Type.error);
        log.warn("error result: " + reply.toXML());
        return reply;
    }

}
